var PATH_PREFIX ="";

function setPathPrefix(path){
	PATH_PREFIX =  path;
}
$(function() {
	// 给select2组件加载样式
	WASP_WIDGET.initializeSelectStyle();
	// 注册清空事件
    WASP_WIDGET.registerResetClearEvent();
    //初始化产品下拉框
    WASP_WIDGET.triggerPrdInfoSelect("prjCode");
});

var $tradeStructureList = $('#tradeStructureList');

$(function() {
	$tradeStructureList.jqGrid({   
		url:PATH_PREFIX+'queryAsseUnitListPage.do',
		//caption:'交易结构列表<button type="button" class="btn btn-default btn-sm btn-small btn-fullscreen" title="" tabindex="-1"><i class="fa fa-arrows-alt icon-fullscreen"></i></button>',  
		datatype: "json",
		postData:{
			'sp[prjCode]' : $("#prjCode").val(),
			'sp[assetType]' : $("#assetType").val()
		},  
		colNames:["主键","产品ID","产品名称","资产单元名称","资产单元类型","资产单元编号","资产单元最低资金额度","资产单元风控类型","银行账号","管理人","操作"],        
		colModel:[  { name: 'assetUnitId', index: 'assetUnitId', hidden: true, key: true, resizable: true, sortable: false },       
					{ name: 'prjCode', index: 'prjCode', hidden: true,resizable: true, sortable: false },
		            { name: 'prjName', index: 'prjName', resizable: true, sortable: false },
		            { name: 'assetName', index: 'assetName', resizable: true, sortable: false },
		            { name: 'assetType', index: 'assetType', resizable: true, sortable: false ,
						formatter:function(cellvalue, options, rowObject){
			        		if(cellvalue =="01"){
			        			return "场外";
			        		}else if(cellvalue =="02"){
			        			return "场内场外";
			        		}else{
			        			return cellvalue;
			        		}
			        	}
		            },
		            { name: 'assetNumber', index: 'assetNumber', resizable: true, sortable: false },
		            { name: 'assetMinQuota', index: 'assetMinQuota', resizable: true, sortable: false },
		            { name: 'assetRiskmanageType', index: 'assetRiskmanageType', resizable: true, sortable: false ,
						formatter:function(cellvalue, options, rowObject){
			        		if(cellvalue =="01"){
			        			return "资产配置";
			        		}else if(cellvalue =="02"){
			        			return "投资交易";
			        		}else if(cellvalue =="03"){
			        			return "其他";
			        		}else if(cellvalue == null){
			        			return "";
			        		}else{
			        			return cellvalue;
			        		}
			        	}
		            },
		            { name: 'bankAccount', index: 'bankAccount', resizable: true, sortable: false },
		            { name: 'managementPeople', index: 'managementPeople', resizable: true, sortable: false },
		            { name: 'option', index: 'option', resizable: true, width:200, sortable: false }
				  ],
		rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        prmNames: { search: "search", page: "pageNo", rows: "limit" },
        height: $(window).height()-270,
        width: false,
        autowidth:true,
        editurl: '',
        viewrecords: true,
        cellEdit: false,
        shrinkToFit: true,
        grouping: false,
        jsonReader: {
            root: "items", //结果集
            records: "total", //总记录数 
            total: "pageCount", //总页数
            page: "pageNo", //当前页 
            repeatitems: false // (4) 
        },  
		multiselect:false,
		viewrecords: true,
		pager: "#tradeStructureListPage",						
		gridComplete: function(){
			var ids = $tradeStructureList.jqGrid('getDataIDs');
			for (var i = 0; i < ids.length; i++) {
				var rowId = ids[i];
				detailBtn = '<a class="btn btn-link btn-jqgrid" title="详情" onclick="detailView(\'' + rowId + '\');" >详情</a><span class="split"></span>';
				updateBtn = '<a class="btn btn-link btn-jqgrid" title="修改" onclick="updateView(\'' + rowId + '\');" >修改</a><span class="split"></span>';
				deleteBtn = '<a class="btn btn-link btn-jqgrid" title="删除" onclick="deleteView(\'' + rowId + '\');" >删除</a>';
				$tradeStructureList.jqGrid('setRowData', ids[i], {
					option : detailBtn + updateBtn + deleteBtn
				});
			}
		},
		subGrid : false,
		subGrid : true,
		subGridRowExpanded : subGridRowExpanded,
		subGridRowColapsed : function(subgrid_id, row_id) {
			$("#subGridTBId").val("");
		},
		ondblClickRow : function(startupId) {
			expandSpecialMatter(startupId);
		}
	});
	$tradeStructureList.navGrid('#tradeStructureListPage',{edit:false,add:false,del:false,search:false,refreshstate:'current'});
	$tradeStructureList.jqGrid('setFrozenColumns');
	jqGridResize($tradeStructureList);
	$(".ui-jqgrid .ui-jqgrid-htable").css("width",$(".ui-jqgrid").width()-1);
	$(".ui-jqgrid .ui-jqgrid-btable").css("width",$(".ui-jqgrid").width()-1);
});

//点击展开特殊事项列表
function expandSpecialMatter(rowid) {
	var ids = $tradeStructureList.jqGrid('getDataIDs');
	for (var i = 0; i < ids.length; i++) {
		var id = ids[i];
		if (id == rowid) {
			$tradeStructureList.jqGrid('toggleSubGridRow', id);
		} else {
			$tradeStructureList.jqGrid('collapseSubGridRow', id);
		}
	}
}

/* 特殊事项列 */
function subGridRowExpanded(subgrid_id, row_id) {
	var rowData = $tradeStructureList.jqGrid('getRowData', row_id);
	var assetUnitId=rowData.assetUnitId;
	var subgrid_table_id = subgrid_id + "_t";
	$("#subGridTBId").val(subgrid_table_id);
	var pager_id = "p_" + subgrid_table_id;
	$("#" + subgrid_id).html(
			"<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + pager_id + "' class='scroll'></div>");
	var parameter = $("#" + subgrid_table_id);
	parameter.jqGrid({
		//caption :'交易单元列表',
		url : PATH_PREFIX+'queryTradeUnitListPage.do',
		mtype:'GET',
		datatype : "json",
		postData : {
			'sp[assetUnitId]' : assetUnitId,
		},
		colNames:["主键","交易代码","交易单元名称","交易单元类型","股东代码卡","管理人"/*,"操作"*/],        
		colModel:[  { name: 'tradeUnitId', index: 'tradeUnitId', hidden: true, key: true, resizable: true, sortable: false },       
		            { name: 'tradeCode', index: 'tradeCode', resizable: true, sortable: false },
		            { name: 'tradeName', index: 'tradeName', resizable: true, sortable: false },
		            { name: 'tradeType', index: 'tradeType', resizable: true, sortable: false ,
						formatter:function(cellvalue, options, rowObject){
			        		if(cellvalue =="01"){
			        			return "场内";
			        		}else if(cellvalue =="02"){
			        			return "场外";
			        		}else{
			        			return cellvalue;
			        		}
			        	}
		            },
		            { name: 'partnerCodeCard', index: 'partnerCodeCard', resizable: true, sortable: false },
		            { name: 'managementPeople', index: 'managementPeople', resizable: true, sortable: false }/*,
		            { name: 'option', index: 'option', resizable: true, width:80, sortable: false }*/
				  ],
		rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        prmNames: { search: "search", page: "pageNo", rows: "limit" },
        height: 'auto',
        width: false,
        autowidth:true,
        editurl: '',
        viewrecords: true,
        cellEdit: false,
        shrinkToFit: true,
        grouping: false,
        jsonReader: {
            root: "items", //结果集
            records: "total", //总记录数 
            total: "pageCount", //总页数
            page: "pageNo", //当前页 
            repeatitems: false // (4) 
        },
		multiselect:false,
		viewrecords: true,
		pager : "#" + pager_id
	});
	parameter.navGrid('#' + pager_id,{edit:false,add:false,del:false,search:false,refreshstate:'current'});
}

/**
 * 查询按钮
 * 根据条件查询数据
 * @param flag
 */
function queryByCondtion(flag){
    var postData = $tradeStructureList.jqGrid("getGridParam", "postData");
    $.extend(postData, {
		'sp[prjCode]' : $("#prjCode").val(),
		'sp[assetType]' : $("#assetType").val()
	});
    if (flag) {
    	$tradeStructureList.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid",[{page:1}]);//重新载入Grid表格
    } else {
    	$tradeStructureList.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid");//重新载入Grid表格
    }
}
/**
 * 打开新增资产单元页面
 * @returns
 */
function addAsseUnit(){
	var url = PATH_PREFIX+"asseUnitAddView.do";
	window.open(url);
}

/**
 * 打开新增交易单元页面
 * @returns
 */
function addTradeUnit(){
	var url = PATH_PREFIX+"tradeUnitAddView.do";
	window.open(url);
}

/**
 * 打开交易资产关联页面
 * @returns
 */
function asseAndTradeUnitRel(){
	var url = PATH_PREFIX+"asseAndtradeUnitRelAddView.do";
	window.open(url);
}


function updateView(id){
	 var url = PATH_PREFIX+"asseUnitDetailView.do?id="+id+"&type=update";
	 window.open(url);
}

function detailView(id){
	var url = PATH_PREFIX+"asseUnitDetailView.do?id="+id+"&type=detail";
	window.open(url);
}

function deleteView(id){
	ctools.confirm({text:"是否确认删除资产单元信息？"},function(isConfirm){
		if(isConfirm){
			if (id == null || id == "") {
				return;
			}
			var actionUrl= PATH_PREFIX + "deleteAsseUnit.do";
			$.ajax({
				type: 'POST',
				url: actionUrl,
				dataType:'json',
				data:{
					"id" : id
				},
				success: function(data){
					if(data.resultCode == "0000"){
						ctools.alert_sweet('资产单元信息删除成功！', "success", "" , function(){
							queryByCondtion(true);
						});
					}else{
						ctools.alert_sweet('资产单元信息删除失败！', "error", "失败原因："+data.resultMsg);
					}
				},
				error:function(xhr){
					switch(xhr.status){
						case 403:sweetAlert("对不起，您无此权限！","","error");break;
						case 404:sweetAlert("对不起，无此页面！", "","error");break;
						case 500:sweetAlert("内部错误，请联系管理员！","","error");break;  
						case 504:sweetAlert("超时，请联系管理员！", "","error");break;  
						case 417:sweetAlert("内部错误，请联系管理员！", "","error");break;  
					}
				}
			});
		}
	});
}